package com.example.jc

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.paging.compose.LazyPagingItems
import coil.annotation.ExperimentalCoilApi
import coil.compose.AsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.example.jc.ui.theme.JComposeAppTheme
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    private val mainViewModel by viewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JComposeAppTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {

                    MainViewAll()

//                    ScrollingList()
                }
            }
        }
    }


}

@Composable
fun MainViewAll() {

    Column {
        MainViewTop()
        MainViewList()
    }
}

//@ExperimentalPagerApi
@OptIn(ExperimentalCoilApi::class)
@Composable
fun MainViewTop() {
//    val pagerState = rememberPagerState(
////        //总页数
////        pageCount = list.size,
////        //预加载的个数
////        initialOffscreenLimit = 1,
////        //是否无限循环
////        infiniteLoop = true,
//        //初始页面
//        initialPage = 0
//    )

    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
//        HorizontalPager(
//            state = pagerState,
//            modifier = Modifier
//                .fillMaxSize(),
//        ) { page ->
//            Image(
//                painter = rememberImagePainter("http://pic-bucket.ws.126.net/photo/0003/2021-11-16/GOTKEOOU00AJ0003NOS.jpg"),
//                modifier = Modifier.fillMaxSize(),
//                contentScale = ContentScale.Crop,
//                contentDescription = null
//            )
//        }
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current.applicationContext)
                .data("http://pic-bucket.ws.126.net/photo/0003/2021-11-16/GOTKEOOU00AJ0003NOS.jpg")
                .crossfade(true)
//                .memoryCachePolicy(CachePolicy.DISABLED)//禁用请求的内存缓存
                .memoryCachePolicy(CachePolicy.ENABLED)//设置内存的缓存策略
                .diskCachePolicy(CachePolicy.ENABLED)//设置磁盘的缓存策略
//                .networkCachePolicy(CachePolicy.ENABLED)//设置网络的缓存策略
//                .target( //图片加载之后的处理
//                    onStart = { placeholder ->
//                        // Handle the placeholder drawable.
//                    },
//                    onSuccess = { result ->
//                        // Handle the successful result.
//                    },
//                    onError = { error ->
//                        // Handle the error drawable.
//                    })
                .build(),

            placeholder = painterResource(R.drawable.placeholder),
            contentDescription = stringResource(R.string.app_name),
            contentScale = ContentScale.Crop,
            modifier = Modifier.clip(CircleShape).size(50.dp),
        )



//        Image(
//            painter = rememberImagePainter(
//                data ="http://pic-bucket.ws.126.net/photo/0003/2021-11-16/GOTKEOOU00AJ0003NOS.jpg",
//                builder = {
//                    //占位图
//                    placeholder(R.drawable.profile_picture)
//                    //淡出效果
//                    crossfade(true)
//                    //圆形效果
//                    transformations(CircleCropTransformation())
//                }
//
//            ),
////            painter = painterResource(R.drawable.profile_picture),
//            contentDescription = "Android Logo",
//            modifier = Modifier.size(50.dp)
//        )
        Spacer(Modifier.width(10.dp))
        Text("Item #", style = MaterialTheme.typography.subtitle1)
    }

}

@Composable
fun MainViewList() {


}

data class Message(val author: String, val body: String)


@Composable
fun ScrollingList() {
    val listSize = 100
    // We save the scrolling position with this state
    val scrollState = rememberLazyListState()
    // We save the coroutine scope where our animated scroll will be executed
    val coroutineScope = rememberCoroutineScope()

    Column {
        Row {
            Button(onClick = {
                coroutineScope.launch {
                    // 0 is the first item index
                    scrollState.animateScrollToItem(0)
                }
            }) {
                Text("Scroll to the top")
            }

            Button(onClick = {
                coroutineScope.launch {
                    // listSize - 1 is the last index of the list
                    scrollState.animateScrollToItem(listSize - 1)
                }
            }) {
                Text("Scroll to the end")
            }
        }


        LazyColumn(state = scrollState) {
            items(listSize) {
                ImageListItem(it)
            }
        }
//        LaunchedEffect(scrollState) {
//            snapshotFlow { scrollState.firstVisibleItemIndex }
//                .map { index -> index > 0 }
//                .distinctUntilChanged()
//                .filter { it == true }
//                .collect {
////                  Toast.makeText(this,"index",Toast.LENGTH_SHORT).show()
//                }
//        }
    }
}

@Composable
fun <T : Any> SwipeRefreshList(
    collectAsLazyPagingItems: LazyPagingItems<T>,
    content: LazyListScope.() -> Unit
) {
    val rememberSwipeRefreshState = rememberSwipeRefreshState(isRefreshing = false)


}
//    ————————————————
//    版权声明：本文为CSDN博主「海坤」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//    原文链接：https://blog.csdn.net/qq_34023088/article/details/117034627


@Composable
fun ErrorItem(retry: () -> Unit) {
    Button(onClick = { retry() }, modifier = Modifier.padding(10.dp)) {
        Text(text = "重试")
    }
}

@Composable
fun ErrorContent(retry: () -> Unit) {
    Image(
        modifier = Modifier.padding(top = 80.dp),
        painter = painterResource(id = R.drawable.profile_picture),
        contentDescription = null
    )
    Text(text = "请求出错啦")
    Button(onClick = { retry() }, modifier = Modifier.padding(10.dp)) {
        Text(text = "重试")
    }
}

@Composable
fun LoadingItem() {
    CircularProgressIndicator(modifier = Modifier.padding(10.dp))
}
//————————————————
//版权声明：本文为CSDN博主「海坤」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//原文链接：https://blog.csdn.net/qq_34023088/article/details/117034627

@Composable
fun ImageListItem(index: Int) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
        Image(
//            painter = rememberImagePainter(
//                data = "https://developer.android.com/images/brand/Android_Robot.png"
//            ),
            painter = painterResource(R.drawable.profile_picture),
            contentDescription = "Android Logo",
            modifier = Modifier.size(50.dp)
        )
        Spacer(Modifier.width(10.dp))
        Text("Item #$index", style = MaterialTheme.typography.subtitle1)
    }
}


//@Preview(
//    showBackground = true,
//    name = "Light Mode"
//)
//@Preview(
//    uiMode = Configuration.UI_MODE_NIGHT_YES,
//    showBackground = true,
//    name = "Dark Mode"
//)
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    JComposeAppTheme {
        MainViewAll()
//        ScrollingList(mainViewModel)
    }
}